'use strict'

const Sequelize = require('sequelize'); //操作数据库
const fs = require('fs'); //文件操作
const ApiClient = require('../server/taobao.js').ApiClient; //淘宝API
const Taobao = require('../server/taobao.js').Taobao;
//前台API，可获取授权
/*var config = {
    app_key:"23164248",
    app_secret:"ea9dbcf8c9dddf13b57fcdd8f1f63b32",
    redirect_uri:"http://vrbuy.ews.m.jaeapp.com/oauth2"
}
var frontClient = new ApiClient({
                            'appkey':config.app_key,
                            'appsecret':config.app_secret,
                            'url':'http://gw.api.taobao.com/router/rest'
                        });*/
//后台API，可获取头像 
var config2 = {
    app_key: "24606908",
    app_secret: "89d74af6ed73f2f9a881c2076fe833b2"
}
var backClient = new ApiClient({
    'appkey': config2.app_key,
    'appsecret': config2.app_secret,
    'url': 'http://gw.api.taobao.com/router/rest'
});

var secretKey = {
    key: '751f620ea3c8f930',
    iv: '2624750004398718',
}

//微信
var WxApi = require('../server/wxApi');
var config = {
    appId: 'wx6d5c659db53fee95',
    appSecret: 'd62213dea308cb61f6c3e5b4fe649468',
    cachepath: 'morefunWxtoken'
}
var wxApi = new WxApi(config, {});

exports.register = function (server, option, next) {

    /*
        const sequelize = server.app.sequelize;

        var dataBase = {
            //团购iteam表
            groupon_fotile_iteam : sequelize.define('groupon_fotile_iteam',{
                iteam_id:{
                    type: Sequelize.INTEGER,
                    primaryKey: true,
                    autoIncrement: true
                }
            },{
                freezeTableName:true,
                timestamps:true,
                underscoredAll:true
            }),
            //团购user表
            groupon_fotile_user : sequelize.define('groupon_fotile_user',{
                user_id:{
                    type: Sequelize.INTEGER,
                    primaryKey: true,
                    autoIncrement: true
                },
                wechat_id:{
                    type: Sequelize.STRING
                },
                taobao_id:{
                    type: Sequelize.STRING
                },
                wangwang_id:{
                    type: Sequelize.STRING
                },
                avatar:{//头像
                    type: Sequelize.STRING
                },
                realname:{
                    type: Sequelize.STRING
                },
                telephone:{
                    type: Sequelize.STRING
                },
                iteam_id:{
                    type: Sequelize.INTEGER
                },
                service:{
                    type: Sequelize.STRING
                }
            },{
                freezeTableName:true,
                timestamps:true,
                underscoredAll:true
            })
        }

        var dataFn = require('../server/groupon')(dataBase,sequelize);
    */



    var dataFn = require('../server/groupon');
    /*
     * /groupon/iteam/add
     * @interface 后台开团
     * @method POST 
     * @param null
     * @return json {errCode:0,msg:'ok',data:{id:**}}
     */
    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/iteam/add',
        handler: function (request, reply) {
            dataFn.iteam.add().then(data => {
                if (data) {
                    var id = dataFn.aesutil.encryption(data.iteam_id + '', secretKey.key, secretKey.iv);
                    return reply(dataFn.wrapper({ 'id': encodeURIComponent(id), url: 'https://vrbuy.ews.m.jaeapp.com/groupon/index?id=' + encodeURIComponent(id) }));
                } else {
                    return reply(dataFn.wrapper(null, 4000));
                }
            });
        }
    });



    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/user/skin',
        handler: function (request, reply) {

            dataFn.user.skin().then(data => {
                if (data) {
                    return reply(data);
                }


            });

        }
    });
    /*
     * /groupon/iteam/add
     * @interface 后台开团,直接跳转
     * @method POST 
     * @param null
     * @return json {errCode:0,msg:'ok',data:{id:**}}
     */
    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/iteam/useradd',
        handler: function (request, reply) {
            dataFn.iteam.add().then(data => {
                if (data) {
                    var id = dataFn.aesutil.encryption(data.iteam_id + '', secretKey.key, secretKey.iv);
                    return reply.redirect('https://vrbuy.ews.m.jaeapp.com/groupon/index?id=' + encodeURIComponent(id));
                } else {
                    return reply(dataFn.wrapper(null, 4000));
                }
            });
        }
    });


    /*
     * 团购首页
     *
     */

    server.route({
        method: ['GET', 'POST'],
        path: '/index',
        handler: function (request, reply) {
            var options = request.payload || request.url.query;

            var content = fs.readFileSync(__dirname.substr(0, Math.max(__dirname.lastIndexOf('\\'), __dirname.lastIndexOf('\/'))) + '/public/index.html', 'utf-8');
            if (!options.code) { //获取微信code
                return reply(content);
            } else {
                wxApi.oauth.getAccessToken(options.code, function (err, result) { //获取微信token
                    if (!err) {
                        var accessToken = result.data.access_token;
                        var openid = result.data.openid;
                        console.log(openid);
                        wxApi.oauth.getUser(openid, function (err, result) { //获取微信用户info
                            if (!err) {
                                //更新头像
                                // reobj.userinfo = result;
                                if (result.headimgurl == '') {
                                    return reply(content)
                                        .header('Set-Cookie', ['openid4=' + openid]);
                                } else {
                                    dataFn.user.updateOne(openid, '', result.headimgurl.replace('http:', 'https:')).then((data) => {
                                        return reply(content)
                                            .header('Set-Cookie', ['openid4=' + openid]);
                                    });
                                }
                                // console.log(result);
                            } else {
                                console.log(err);
                                return reply(content)
                                    .header('Set-Cookie', ['openid4=' + openid]);
                            }
                        });
                    } else {
                        console.log(err);
                    }
                });
            }
        }
    });

    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/iteam/list',
        handler: function (request, reply) {
            var options = request.payload || request.url.query;
            console.log(options);
            if (typeof options.id != 'undefined') {
                options.id = dataFn.aesutil.decryption(decodeURIComponent(options.id + ''), secretKey.key, secretKey.iv);
            }
            if (typeof request.state.openid4 == 'undefined') {
                options.openid = '111';
            } else {
                options.openid = request.state.openid4;
            }
            if (typeof request.state.mixnick3 == 'undefined') {
                options.mixnick = 'aa';
            } else {
                options.mixnick = decodeURIComponent(request.state.mixnick3);
            }
            var reData = {};
            var list = dataFn.iteam.getList(options.id);
            var user = dataFn.user.selectOne(options.openid, options.mixnick);
            Promise.all([list, user]).then((data) => {
                var listData = data[0];
                var userData = data[1];
                var arr = [];
                for (var i in listData) {
                    arr.push(listData[i].avatar);
                }
                reData.avatar = arr;
                if (userData) {
                    var id = dataFn.aesutil.encryption(userData.iteam_id + '', secretKey.key, secretKey.iv);
                    reData.attend = true;
                    reData.iteamid = encodeURIComponent(id);
                    return reply(dataFn.wrapper(reData));
                } else {
                    reData.attend = false;
                    return reply(dataFn.wrapper(reData));
                }
            });
        }
    });

    /*
     * /groupon/iteam/attend
     * @interface 前台参团
     * @method POST 
     * @param wangwang
     * @param name
     * @param phone
     * @param iteamid
     * @return json {errCode:0,msg:'ok',data:null}
     */
    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/iteam/attend',
        handler: function (request, reply) {
            var options = request.payload || request.url.query;
            console.log(options);
            //验证参数
            if (typeof options != 'object') {
                return reply(dataFn.wrapper(null, 4000));
            }
            if (typeof options.wangwang == 'undefined') {
                return reply(dataFn.wrapper(null, 4001));
            }
            if (typeof options.name == 'undefined') {
                return reply(dataFn.wrapper(null, 4002));
            }
            if (typeof options.phone == 'undefined') {
                return reply(dataFn.wrapper(null, 4003));
            }
            if (typeof options.service == 'undefined') {
                options.service = '';
            }
            if (typeof options.iteamid == 'undefined') {
                return reply(dataFn.wrapper(null, 4004));
            } else {
                options.iteamid = Number(dataFn.aesutil.decryption(decodeURIComponent(options.iteamid) + '', secretKey.key, secretKey.iv));
            }
            if (typeof request.state.openid4 == 'undefined') {
                options.openid = '';
            } else {
                options.openid = request.state.openid4;
            }
            if (typeof request.state.mixnick3 == 'undefined') {
                options.mixnick = '';
            } else {
                options.mixnick = decodeURIComponent(request.state.mixnick3);
            }
            console.log(options);
            dataFn.user.getAvatar(options.mixnick, backClient).then(imgurl => {
                options.avatar = imgurl;
                dataFn.iteam.getList(options.iteamid).then(result => {
                    if (result && result.length > 0) {
                        options.service = result[result.length - 1].service || '';
                        dataFn.iteam.attend(options).then(data => {
                            if (data) {
                                return reply(dataFn.wrapper(null));
                            } else {
                                return reply(dataFn.wrapper(null, 4004));
                            }
                        });
                    } else {
                        dataFn.iteam.attend(options).then(data => {
                            if (data) {
                                return reply(dataFn.wrapper(null));
                            } else {
                                return reply(dataFn.wrapper(null, 4004));
                            }
                        });
                    }
                });
            });
        }
    });

    /*
     * /groupon/iteam/look
     * @interface 查询接口
     * @method POST 
     * @param wangwang
     * @param phone
     * @return json {errCode:0,msg:'ok',data:null}
     */
    server.route({
        method: ['GET', 'POST'],
        path: '/groupon/iteam/look',
        handler: function (request, reply) {
            var options = request.payload || request.url.query;
            console.log(options);
            //验证参数
            if (typeof options != 'object') {
                return reply(dataFn.wrapper(null, 4000));
            }
            if (typeof options.wangwang == 'undefined') {
                options.wangwang = '';
            }
            if (typeof options.phone == 'undefined') {
                options.phone = '';
            }
            console.log(options);
            dataFn.user.selectOneByQuery(options.wangwang, options.phone).then(result => {
                if (result) {
                    var id = result.iteam_id;
                    try {
                        result.iteam_id = encodeURIComponent(dataFn.aesutil.encryption(id + '', secretKey.key, secretKey.iv));
                        result.url = 'https://vrbuy.ews.m.jaeapp.com/groupon/index?id=' + result.iteam_id;
                    } catch (e) {
                        console.log(e);
                    }
                    dataFn.iteam.count(id).then(count => {
                        if (count) {
                            result.count = count;
                        } else {
                            result.count = 0;
                        }
                        return reply(dataFn.wrapper(result));
                    });
                } else {
                    return reply(dataFn.wrapper(null, 4004));
                }
            });
        }
    });

    return next();
}

exports.register.attributes = {
    name: 'route-groupon'
}